package com.qsj.easydarwin.util;

import com.qsj.easydarwin.config.Config;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 原生ffmpeg
 *
 * @author Q1sj
 * @version 1.0
 * @date 2020/7/15 16:59
 */
public class FfmpegUtils {

    private Process process;

    private boolean exit = false;

    /**
     * 推流
     *
     * @param videoPath
     * @param target
     */
    public void push(String videoPath, String target) {
        exit = false;
        try {
            // 视频切换时，先销毁进程，全局变量Process process，方便进程销毁重启，即切换推流视频
            if (process != null) {
                process.destroy();
                System.out.println(">>>>>>>>>>推流视频切换<<<<<<<<<<");
            }
            // ffmpeg开头，-re代表按照帧率发送，在推流时必须有
            // 指定要推送的视频
            // 指定推送服务器，-f：指定格式
            String command = String.format("ffmpeg -re  -stream_loop -1 -i %s  -vcodec copy -codec copy -f rtsp %s",
                    videoPath, target);
            System.out.println("ffmpeg推流命令：" + command);
            // 运行cmd命令，获取其进程
            process = Runtime.getRuntime().exec(command);
            // 输出ffmpeg推流日志
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line = "";
            while ((line = br.readLine()) != null && !exit) {

                System.out.println(target+"视频推流信息[" + line + "]");
            }
            exit=true;
            process.destroy();
//            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 截图
     * @param filePath
     * @param time
     * @param imagePath
     * @return
     */
    public String saveCurrentImage(String filePath,Long time,String imagePath){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String format = sdf.format(time*1000);
        String fileName = System.currentTimeMillis()+".jpg";

//        ffmpeg -ss 00:02:06 -i  D:/Video/test.mp4 -f image2 -y D:/test.jpg
        String cmd = "ffmpeg -ss " + format + " -i  " + filePath + " -f image2 -y " + imagePath+fileName;
        System.out.println(cmd);
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public boolean isExit() {
        return exit;
    }

    public void setExit(boolean exit) {
        this.exit = exit;
    }
}
